package com.itheima.dubbo.mongodb.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.commons.constants.Constants;
import org.bson.types.ObjectId;

import cn.hutool.core.collection.CollUtil;
import com.itheima.commons.pojo.TimeLine;
import com.itheima.commons.pojo.Users;
import com.itheima.dubbo.interfaces.TimeLineApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class TimeLineApiImpl implements TimeLineApi {

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public void save(String publishId, Long userId) {
        //先根据用户id查询所有好友
        List<Users> users = mongoTemplate.find(Query.query(Criteria.where("userId").is(userId)), Users.class);

        //把好友id封装成集合
        List<Long> friendIds = CollUtil.getFieldValues(users, "friendId",Long.class);

        //根据好友id集合，把publishId存入对应表（表名：quanzi_time_line_id）

        TimeLine timeLine = new TimeLine();
        timeLine.setId(new ObjectId());
        timeLine.setUserId(userId);
        timeLine.setPublishId(new ObjectId());
        timeLine.setDate(System.currentTimeMillis());

        for (Long friendId : friendIds) {
            mongoTemplate.save(timeLine, Constants.TIME_LINE_PRE_+friendId);
        }

    }
}
